#include "stm32f10x.h"                  // Device header

void Encoder_Init(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitTypeDef GPIO_InitStructure;
 	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
 	GPIO_Init(GPIOA, &GPIO_InitStructure);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitstructure;
    TIM_TimeBaseInitstructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitstructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitstructure.TIM_Period = 65536 - 1;  // maximum
    TIM_TimeBaseInitstructure.TIM_Prescaler = 1 - 1; //pre division
    TIM_TimeBaseInitstructure.TIM_RepetitionCounter = 0; //only applays to NB Timer(Tim1 and Tim8 in APB2)
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitstructure); /*已初始化就进入中断原因 Generate an update event to reload the Prescaler and the Repetition counter values immediately */
    TIM_ClearFlag(TIM3, TIM_FLAG_Update); //clear 更新flag to 避免马上进入更新中断

    TIM_ICInitTypeDef TIM_ICInitStructure;
    TIM_ICStructInit(&TIM_ICInitStructure);
    TIM_ICInitStructure.TIM_Channel = TIM_Channel_1 | TIM_Channel_2;
    TIM_ICInitStructure.TIM_ICFilter = 0x03;
    TIM_ICInit(TIM3, &TIM_ICInitStructure);

    TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12, TIM_ICPolarity_Falling, TIM_ICPolarity_Falling);


    TIM_Cmd(TIM3, ENABLE);
}

int16_t Encoder_AngleGet(void)
{
    return (int16_t)TIM_GetCounter(TIM3);
}
